package com.example.controller;

import cn.hutool.core.util.StrUtil;
import com.example.config.Result;
import com.example.pojo.Role;
import com.example.utils.DateUtil;
import com.example.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;

@RestController
@Api(tags = "统计")
@RequestMapping("/api/statistics")
public class StatisticsController {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private DateUtil dateUtil;

    /**
     * 添加访问量
     * @param userId
     * @return
     */
    @GetMapping("/{userId}")
    public Result<?> add(@PathVariable Long userId) {
        Long visitsCount = redisTemplate.opsForHyperLogLog().add("VisitsCount", userId);
        //设置凌晨失效
        long expireTime = (dateUtil.getEveryDayTime() - System.currentTimeMillis())/1000;
        redisUtil.expire("VisitsCount",expireTime);
        return Result.success(visitsCount);
    }

    /**
     * 拿到访问量
     * @return
     */
    @GetMapping()
    public Result<?> getSize() {
        Long visitsCount = redisTemplate.opsForHyperLogLog().size("VisitsCount");
        return Result.success(visitsCount);
    }

    /**
     * 拿到今天的营业额
     * @return
     */
    @GetMapping("/turnover")
    public Result<?> getTurnover() {
        List<Object> turnover = redisUtil.lGet("turnover", 0, -1);
        BigDecimal bigDecimal = new BigDecimal(0);
        for (int i = 0; i < turnover.size(); i++){
            String o = String.valueOf(turnover.get(i));
            double v = Double.parseDouble(o);
            bigDecimal = bigDecimal.add(new BigDecimal(Double.valueOf(v)));
        }
        bigDecimal = bigDecimal.setScale(2,BigDecimal.ROUND_DOWN);
        return Result.success(bigDecimal);
    }

    /**
     * 拿到今天的销售量
     * @return
     */
    @GetMapping("/sales")
    public Result<?> getSales() {
        if (redisUtil.hasKey("sales")){
            Object sales = redisUtil.get("sales");
            return Result.success(sales);
        }else {
            return Result.success(0);
        }

    }

}
